package com.elcom.player;

import java.io.IOException;

import com.elcom.player.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class VideoPlayerActivity extends Activity implements
			OnCompletionListener, OnErrorListener, OnInfoListener,
			OnBufferingUpdateListener, OnPreparedListener, OnSeekCompleteListener,
			OnVideoSizeChangedListener, SurfaceHolder.Callback,
			MediaController.MediaPlayerControl{

	private static final int SETTING_REQ    = 0x10;	
	private static SharedPreferences settings;
	
	MediaController controller;
	Display currentDisplay;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	MediaPlayer mediaPlayer;
	String mPath, mTitle;
	
	View mainView;
	TextView mcCurrentTime;
	TextView mcTotalTime;
	TextView mcFileName;
	ImageButton mcPlay;
	SeekBar mcSeek;
	RelativeLayout mcLayout;
	
	TextView mTextSubtitle;
	private Subtitle mSubtitle;
	
	int videoWidth = 0;
	int videoHeight = 0;
	int totalDuration;
	int playedDuration;
	private static boolean paused;
	private boolean bSeeking;
	boolean readyToPlay = false;
	public final static String LOGTAG = "STREAMING_VIDEO_PLAYER";
	private Updater seekBarUpdater = new Updater();
	private Handler mHandler = new Handler();
	
	private int postionBeforeSetting=0;
	
	private void log(String ss){
		Log.d("EVPLayer", ss);
	}
	private void toast(String ss){
		Toast.makeText(VideoPlayerActivity.this, ss, Toast.LENGTH_SHORT).show();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.videoview);
		readSettings();
		Intent intent = getIntent();
		mPath = intent.getStringExtra("videofilename");
		Globals.fileName = mPath;
		//mTitle = intent.getStringExtra("title");
		mTitle = "title";
		toast(mPath);
		paused = false;
		if (TextUtils.isEmpty(mPath))
			mPath = Environment.getExternalStorageDirectory() + "test.mp4";
		else if (intent.getData() != null)
			mPath = intent.getData().toString();
		
		mainView = this.findViewById(R.id.MainView);
		mcCurrentTime = (TextView)findViewById(R.id.mediacontroller_time_current);
		mcTotalTime = (TextView)findViewById(R.id.mediacontroller_time_total);
		mcFileName = (TextView)findViewById(R.id.mediacontroller_file_name);
		mcSeek = (SeekBar)findViewById(R.id.mediacontroller_seekbar);
		mcLayout = (RelativeLayout)findViewById(R.id.mediacontroller_layout);
		mcPlay = (ImageButton)findViewById(R.id.mediacontroller_play_pause);
		mTextSubtitle = (TextView)findViewById(R.id.subtitle);
		mTextSubtitle.setText("nguye ngoc \n anhd \n nguye ngoc an");
		mSubtitle = new Subtitle("/mnt/sdcard/test.srt",mTextSubtitle);
		
		mcSeek.setOnSeekBarChangeListener(mcSeekChangeListener);
		mainView.setOnClickListener(mMainViewListener);
		mcPlay.setOnClickListener(mcPlayListener);
		surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mediaPlayer.setOnInfoListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnSeekCompleteListener(this);
		mediaPlayer.setOnVideoSizeChangedListener(this);
		mediaPlayer.setOnBufferingUpdateListener(this);
		try {
			mediaPlayer.setDataSource(mPath);
		} catch (IllegalArgumentException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IOException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		}
		currentDisplay = getWindowManager().getDefaultDisplay();
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		paused = false;
		
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mediaPlayer.setOnInfoListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnSeekCompleteListener(this);
		mediaPlayer.setOnVideoSizeChangedListener(this);
		mediaPlayer.setOnBufferingUpdateListener(this);
		try {
			mediaPlayer.setDataSource(mPath);
		} catch (IllegalArgumentException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IOException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mediaPlayer.stop();
	}
	//menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated   method stub
		getMenuInflater().inflate(R.menu.menu_videoplayer, menu);
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated  method stub
		switch (item.getItemId()) {
        case R.id.menu_settings:
        	Intent i = new Intent(VideoPlayerActivity.this, Setting.class);
			i.putExtra("SUBTITLE", Globals.dbSubtitle);
			i.putExtra("SUBTITLESIZE", Globals.dbSubtitleSize);
			i.putExtra("SUBTITLEFONT", Globals.dbSubtitleFont);
			i.putExtra("SUBTITLEFILE", Globals.dbSubtitleFile);
			i.putExtra("SUBTITLEPOS", Globals.dbSubtitlePos);
			i.putExtra("SUBTITLECOL", Globals.dbSubtitleCol);
			// pause video when onto etting
			postionBeforeSetting = mediaPlayer.getCurrentPosition();
			mediaPlayer.stop();
			seekBarUpdater.stopIt();	
			paused = true;
        	startActivityForResult(i, SETTING_REQ);
        	return true;
        case R.id.menu_about:
        	return true;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//  TODO Auto-generate method stub
		
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == SETTING_REQ && resultCode == RESULT_CANCELED) {
			//  save the infrmation   weg tfro msettings   activity
			boolean subtitle     = data.getBooleanExtra("SUBTITLE", Globals.dbSubtitle);
			int     subtitlesize = data.getIntExtra("SUBTITLESIZE", Globals.dbSubtitleSize);
			String subtitlefont = data.getStringExtra("SUBTITLEFONT");
			String subtitlefile = data.getStringExtra("SUBTITLEFILE");
			int subtitlepos = data.getIntExtra("SUBTITLEPOS",Globals.dbSubtitlePos);
		    int subtitlecol = data.getIntExtra("SUBTITLECOL",Globals.dbSubtitleCol);
    
		    writeSettings(subtitle,
						  subtitlesize,
						  subtitlefont,
						  subtitlefile,
						  subtitlepos,
						  subtitlecol);
		    mSubtitle.LoadSubtitle(subtitlefile);
		    mSubtitle.setFont(subtitlefont);
		    mSubtitle.setColor(FileManager.getSubTitleColor());
		    mSubtitle.setSize((float)FileManager.getSubTitleSize());
		    mSubtitle.setPosition(subtitlepos);
		    mSubtitle.setEnable(subtitle);
		}
	}
	public void writeSettings(boolean subtitle,
							  int subtitlesize,
							  String subtitlefont,
							  String subtitlefile,
							  int subtitlepos,
							  int subtitlecol)
	{
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(Globals.PREFS_SUBTITLE, subtitle);
		editor.putInt(Globals.PREFS_SUBTITLESIZE, subtitlesize);
		editor.putString(Globals.PREFS_SUBTITLEFONT, subtitlefont);
		editor.putString(Globals.PREFS_SUBTITLEFILE, subtitlefile);
		editor.putInt(Globals.PREFS_SUBTITLEPOS, subtitlepos);
		editor.putInt(Globals.PREFS_SUBTITLECOL, subtitlecol);
		editor.commit();
		
		Globals.setShowSubTitle(subtitle);
		Globals.setSubTitleSize(subtitlesize);
		Globals.setSubTitleFont(subtitlefont);
		Globals.setSubTitleFile(subtitlefile);
		Globals.setSubTitlePos(subtitlepos);
		Globals.setSubTitleCol(subtitlecol);
	}
	public void readSettings() {

		settings = getSharedPreferences(Globals.PREFS_NAME, MODE_PRIVATE);
		Globals.dbSubtitle     = settings.getBoolean(Globals.PREFS_SUBTITLE, Globals.dbSubtitle);
		Globals.dbSubtitleSize = settings.getInt(Globals.PREFS_SUBTITLESIZE, Globals.dbSubtitleSize);
		Globals.dbSubtitleFont = settings.getString(Globals.PREFS_SUBTITLEFONT, Globals.dbSubtitleFont);
		Globals.dbSubtitleFile = settings.getString(Globals.PREFS_SUBTITLEFILE,Globals.dbSubtitleFile);
		Globals.dbSubtitlePos = settings.getInt(Globals.PREFS_SUBTITLEPOS,Globals.dbSubtitlePos);
		Globals.dbSubtitleCol = settings.getInt(Globals.PREFS_SUBTITLECOL,Globals.dbSubtitleCol);
		
		Globals.setShowSubTitle(Globals.dbSubtitle);
		Globals.setSubTitleSize(Globals.dbSubtitleSize);
		Globals.setSubTitleFont(Globals.dbSubtitleFont);
		Globals.setSubTitleFile(Globals.dbSubtitleFile);
		Globals.setSubTitlePos(Globals.dbSubtitlePos);
		Globals.setSubTitleCol(Globals.dbSubtitleCol);
		//DemoRenderer.UpdateValuesFromSettings();
	}
	public void restartUpdater() {
		seekBarUpdater.stopIt();
		seekBarUpdater = new Updater();
		mHandler.postDelayed(seekBarUpdater, 100);
	}
	OnClickListener mcPlayListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(paused) {
				mediaPlayer.start();
				seekBarUpdater = new Updater();
				mHandler.postDelayed(seekBarUpdater, 10);
				mcPlay.setImageResource(R.drawable.mediacontroller_pause01);
			}else {
				mediaPlayer.pause();
				seekBarUpdater.stopIt();						
				mcPlay.setImageResource(R.drawable.mediacontroller_play01);
			}		        	
			paused = !paused;
		}
	};
	OnSeekBarChangeListener mcSeekChangeListener = new OnSeekBarChangeListener() {
		
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			log("stop SeekBar");
			int progress = seekBar.getProgress();
			mediaPlayer.seekTo(progress*totalDuration);
			bSeeking = false;
			if (!paused) {
				restartUpdater();
			} 
		}
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			log("start SeekBar");
			bSeeking = true;
		}
		
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if(fromUser) {
				int currentSecsMoved = (int)((totalDuration * ((float) (progress / 10F ))) / 100);
				String timeMoved = Utils.formatTime(currentSecsMoved);
				//scrolledtime.setText(timeMoved);
				mcCurrentTime.setText(timeMoved);
				//resetAutoHider();
			}
		}
	};
	OnClickListener mMainViewListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(mcLayout.getVisibility() == View.VISIBLE){
				mcLayout.setVisibility(View.GONE);
			}else{
				mcLayout.setVisibility(View.VISIBLE);
			}
		}
	};
	public void surfaceCreated(SurfaceHolder holder) {
		Log.v(LOGTAG, " surfaceCreated Called");

		mediaPlayer.setDisplay(holder);

		try {
			mediaPlayer.prepareAsync();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, "IllegalStateException " + e.getMessage());
			finish();
		}

	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.v(LOGTAG, "surfaceChanged Called");
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.v(LOGTAG, "surfaceDestroyed Called");
	}

	public void onCompletion(MediaPlayer mp) {
		Log.v(LOGTAG, "onCompletion Called");
		
	}

	public boolean onError(MediaPlayer mp, int whatError, int extra) {
		Log.v(LOGTAG, "onError Called");
		if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
			Log.v(LOGTAG, "Media Error, Server Died " + extra);
		} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
			Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
		}
		return false;
	}

	public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
		if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
			Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
			Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
			Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
			Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
		} 
		return false;
	}
	
	public void onPrepared(MediaPlayer mp) {
		
		Log.v(LOGTAG, "onPrepared Called");
		mp.start();
		mp.seekTo(postionBeforeSetting);
		mcFileName.setText(mTitle);
		mcTotalTime.setText(Utils.formatTime(mp.getDuration()/1000));
		seekBarUpdater = new Updater();
		mHandler.postDelayed(seekBarUpdater, 100);
		
		
	}
	private class Updater implements Runnable {
		private boolean stop;

		public void stopIt() {
			System.out.println("Stopped updater");
			stop = true;
		}
		@Override
		public void run() {
			if(!bSeeking){
				playedDuration = mediaPlayer.getCurrentPosition()/1000;
				mcCurrentTime.setText(Utils.formatTime(mediaPlayer.getCurrentPosition()/1000));
				
				if(!stop) {
					mHandler.postDelayed(seekBarUpdater, 100);
					totalDuration = mediaPlayer.getDuration()/1000;
					if(totalDuration != 0) {
						int progress = (int)((1000 * playedDuration) / totalDuration);
						mcSeek.setProgress(progress);							
						mcTotalTime.setText(Utils.formatTime(totalDuration));
						mSubtitle.findSubTitle(1000*playedDuration);
					}	
				}
			}
		}
	}
	public void onSeekComplete(MediaPlayer mp) {
		Log.v(LOGTAG, "onSeekComplete Called");
	}

	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		Log.v(LOGTAG, "onVideoSizeChanged Called");
	}

	public void onBufferingUpdate(MediaPlayer mp, int bufferedPercent) {
		Log.v(LOGTAG, "MediaPlayer Buffering: " + bufferedPercent + "%");
	}

	public boolean canPause() {
		return true;
	}

	public boolean canSeekBackward() {
		return true;
	}

	public boolean canSeekForward() {
		return true;
	}

	public int getBufferPercentage() {
		return 0;
	}

	public int getCurrentPosition() {
		return mediaPlayer.getCurrentPosition();
	}

	public int getDuration() {
		return mediaPlayer.getDuration();
	}

	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}

	public void pause() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
	}

	public void seekTo(int pos) {
		mediaPlayer.seekTo(pos);
	}

	public void start() {
		mediaPlayer.start();
	}

}
